<template>
  <el-form ref="informationForm" label-position="top" size="small" class="bold-label"
           :model="form" :rules="rules">
    <el-form-item label="昵称" prop="nickname" ref="nickname">
      <el-input v-model="form.nickname" placeholder="请输入昵称"/>
    </el-form-item>
    <el-form-item label="邮箱" prop="email" ref="nickname">
      <el-input v-model="form.email" placeholder="请输入常用邮箱"/>
    </el-form-item>
    <el-form-item label="身份" prop="identity" ref="identity">
      <el-select v-model="form.identity">
        <el-option v-for="identity in $C.users.identities" :key="identity.value"
                   :value="identity.value" :label="identity.cn"/>
      </el-select>
    </el-form-item>
    <el-form-item label="学校或单位" prop="company" ref="company">
      <el-autocomplete v-model="form.company" :trigger-on-focus="false" value-key="name"
                       placehoder="请输入学校或单位" :disabled="!form.identity"
                       :fetch-suggestions="companyMatching"
                       @select="companySelect" @blur="companyBlur"/>
    </el-form-item>
    <el-form-item label="个人主页">
      <el-input v-model="form.website"></el-input>
    </el-form-item>
    <el-form-item label="个人简介">
      <el-input v-model="form.bio" type="textarea"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" :loading="isLoading">更新个人信息</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import * as format from '../../format';

export default {
  name: 'InformationForm', // 个人信息
  data() {
    const currentUser = this.$store.state.currentUser;
    return {
      form: {
        nickname: currentUser.nickname, // 昵称
        email: currentUser.email, // 邮箱
        identity: currentUser.identity, // 身份
        company: currentUser.company, // 学校或单位
        companyCode: null, // 学校识别码
        website: currentUser.website, // 个人主页
        bio: currentUser.bio, // 个人简介
      },
      rules: {
        nickname: [{ required: true, validator: this.$va.nickname, trigger: 'blur' }],
        email: [{ required: false, type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
        identity: [{ required: true }],
        company: [{ required: true, message: '学校或单位不能为空', trigger: ['blur', 'change'] }],
      },
      isLoading: false, // 正在保存个人信息
    };
  },
  computed: {
    // 生成更新用户信息所需参数
    initUpdateParams() {
      const company = this.$C.users.idMatchSchool.includes(this.form.identity)
        ? this.form.companyCode
        : this.form.company;
      return {
        userId: this.$store.state.currentUser.id,
        nickname: this.form.nickname,
        email: this.form.email,
        identity: this.isIdChanged ? this.form.identity : undefined,
        company: this.isIdChanged ? company : undefined,
        website: this.form.website,
        bio: this.form.bio,
      };
    },
    // 判断identity是否发生变化，不然company会往后端传null
    isIdChanged() { return this.form.identity !== this.$store.state.currentUser.identity; },
  },
  methods: {
    // 匹配学校或单位
    companyMatching(value, cb) {
      if (!this.$C.users.idMatchSchool.includes(this.form.identity)) cb([]);
      else {
        this.$api.other.companyMatching({ title: value.trim() })
          .then(res => cb(res.data)).catch(() => {});
      }
    },
    // 选择学校
    companySelect(obj) { this.form.companyCode = obj.code; },
    // 非正常操作会清空选项
    companyBlur() {
      if (this.$C.users.idMatchSchool.includes(this.form.identity)) {
        this.form.company = '';
        this.form.companyCode = '';
      }
    },
    // 保存用户信息
    onSubmit() {
      this.$refs.informationForm.validate((valid, errs) => {
        if (valid) {
          this.isLoading = true;
          this.$api.users.update(this.initUpdateParams)
            .then((res) => {
              this.$message.success('个人信息更新成功');
              this.handleRes(res);
            })
            .catch(() => {})
            .then(() => { this.isLoading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 处理返回的信息（这里是重新保存，返回的信息中没有token）
    handleRes(res) {
      const formatUser = format.formatUser(res.data); // 处理信息
      const user = Object.assign(formatUser, { token: this.$store.state.currentUser.token });
      this.$store.dispatch('setCurrentUser', user);
    },
  },
};
</script>

<style></style>
